package com.yanyeori.framework.web.filter;

import com.yanyeori.framework.core.constant.BaseWebCodeEnum;
import com.yanyeori.framework.core.model.WebResponse;
import com.yanyeori.framework.core.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * web请求拦截器
 *
 * @author chenkuan 2022/10/27
 */
@Slf4j
@Order(-10)
public class WebRequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //Before Filter
        WebResponse<?> webResponse = FilterHandler.handleBeforeFilter(request, response);
        if (!webResponse.isSuccess()) {
            log.warn("Before request filter validation failed: {}", webResponse.getMessage());
            ServletUtil.writeToResponse(response, BaseWebCodeEnum.OK.code(), webResponse);
            return;
        }

        //doFilter
        chain.doFilter(request, response);

        //After Filter
        webResponse = FilterHandler.handleAfterFilter(request, response);
        if (!webResponse.isSuccess()) {
            log.warn("After request filter validation failed: {}", webResponse.getMessage());
            ServletUtil.writeToResponse(response, BaseWebCodeEnum.OK.code(), webResponse);
        }
    }
}
